package com.zero.yygh.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.zero.yygh.common.exception.CommonException;
import com.zero.yygh.common.result.ResultCodeEnum;
import com.zero.yygh.oss.config.ConstantOssPropertiesUtils;
import com.zero.yygh.oss.service.FileService;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * @author zero
 * @desc
 * @create 2021/4/12
 */
@Service
public class FileServiceImpl implements FileService {
    /**
     * 上传文件
     * @param file 上传的文件
     * @return java.lang.String
     * @author zero
     * @date 2021/4/12 14:24
     */
    @Override
    public String upload (MultipartFile file) {

        String endpoint = ConstantOssPropertiesUtils.EDNPOINT;
        String accessKeyId = ConstantOssPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantOssPropertiesUtils.SECRECT;
        String bucketName = ConstantOssPropertiesUtils.BUCKET;
        try{
            // 创建OSSClient实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            // 上传文件流
            InputStream inputStream = file.getInputStream();
            String filename = file.getOriginalFilename();
            // 生成唯一值
            String uuid = UUID.randomUUID().toString().replace("-", "");
            filename = uuid + filename;
            // 按照当前日期，创建文件夹
            String timeUrl = new DateTime().toString("yyyy/MM/dd");
            filename = timeUrl + "/" + filename;
            // 调用方法实现上传
            ossClient.putObject(bucketName, filename, inputStream);
            // 关闭 ossClient
            ossClient.shutdown();
            // 获取上传后的文件路径
            return "https://" + bucketName + "." + endpoint + "/" + filename;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
